﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraVerticalGrid.Rows;
using Silent.MDB.Application.Core;
using Silent.MDB.Common.Data;
using Silent.MDB.Common.Services;

namespace Silent.MDB.Application
{
    public partial class ObjectEditor : Form
    {
        public ObjectEditor(RootObject selectedObject)
        {
            InitializeComponent();

            if(selectedObject == null)
                throw new ArgumentNullException("selectedObject");

            SelectedObject = selectedObject;
            propertyGridObject.SelectedObject = selectedObject;
            SetupPropertyGrid();
        }

        public RootObject SelectedObject { get; private set; }

        private List<string> GetLocations()
        {
            return ApplicationCore.ClientServiceManager.GetService<ISystemInfoService>().Service.GetLocations();
        }
        private void SetupPropertyGrid()
        {
            foreach (BaseRow row in propertyGridObject.Rows.Cast<CategoryRow>().SelectMany(x => SelectMany<BaseRow>(x.ChildRows)))
            {
                if (row.Properties.FieldName == "Location")
                {
                    var repositoryEdit = new RepositoryItemComboBox();
                    repositoryEdit.Items.AddRange(GetLocations());
                    row.Properties.RowEdit = repositoryEdit;
                }
                if (row.Properties.FieldName.Contains("Id")
                    || row.Properties.FieldName == "Objects")
                {
                    row.Properties.ReadOnly = true;
                    row.Visible = false;
                }
            }
        }

        private IEnumerable<T> SelectMany<T>(IEnumerable list) where T : class
        {
            return from object item in list select item as T;
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}
